package com.tid.hbasees.utils.kafka;

import com.tid.hbasees.SysConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Arrays;
import java.util.Properties;

public class Consumer implements Runnable {

    private SysConfig sysConfig;
    private KafkaConsumer<String, String> consumer;

    public Consumer(SysConfig sysConfig) {
        this.sysConfig = sysConfig;
        Properties props = new Properties();
        props.put("bootstrap.servers", sysConfig.getKafkaZks());
        props.put("group.id", "test");
        props.put("enable.auto.commit", "true");  //自动commit
        props.put("auto.commit.interval.ms", "1000"); //定时commit的周期
        props.put("session.timeout.ms", "30000"); //consumer活性超时时间
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
        consumer.subscribe(Arrays.asList(sysConfig.getKafkaTopics()));
    }

    public void run() {
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(100);  //100是超时等待时间
            for (ConsumerRecord<String, String> record : records) {
                //TODO add conmsuing logic
            }
        }
    }
}
